package com.ioidea.ble

import com.blankj.utilcode.util.LogUtils
import com.ioidea.base.util.MyLogger
import com.ioidea.ble.bean.BleRequest
import com.ioidea.ble.bean.BleResponse
import com.ioidea.ble.bean.EnumResponse
import com.ioidea.ble.bean.MAX_RETRY_COUNT
import com.ioidea.ble.lock.BleLock
import java.util.concurrent.BlockingDeque
import java.util.concurrent.LinkedBlockingDeque
import java.util.concurrent.TimeUnit
import kotlin.concurrent.thread

/**
 * 后面考虑用组合好
 */
abstract class BleThreadQueue {
    var request:BleRequest= BleRequest()
    val loopLock = BleLock<ByteArray>()
     val bleRequestQueue: BlockingDeque<BleRequest> = LinkedBlockingDeque<BleRequest>()

    open fun startThread() {
        thread {
            while (true) {
                request = try {
                    this.bleRequestQueue.take()
                } catch (e: InterruptedException) {
                    LogUtils.e("从bleRequestQueue取数据错误", e)
                    continue
                }
                loopLock.lock()
                //这里用锁来阻塞
                sendRequest(request)
                try {
                    val wait=  loopLock.await(BleLock.TIME_OUT, TimeUnit.MILLISECONDS)
                    if (wait){
                        // 正常的处理
                        val respBytes = loopLock.getData()
                        respBytes?.let { BleResponse(EnumResponse.SUCCESS, it) }
                            ?.let { request.callback(it) }
                    }else{
                        //超时处理
                        request.retryCount++
                        MyLogger.hLog().e("请求重试次数:${request.retryCount} $request")
                        if (request.retryCount< MAX_RETRY_COUNT){
                            putFirstRequest(request)
                        }else{
                            request.callback(BleResponse(EnumResponse.TIMEOUT))
                        }

                    }
                } catch (e: Exception) {
                    LogUtils.e("读数据超时异常", e)
                } finally {
                    loopLock.unlock()
                }

            }
        }

    }

    abstract fun sendRequest(request: BleRequest)



    fun putRequest(request: BleRequest){
        bleRequestQueue.add(request)
    }

    /**
     * 插队到前面
     */
    fun putFirstRequest(request: BleRequest){
        bleRequestQueue.addFirst(request)
    }

    /**
     * 插队到后面
     */
    fun putLastRequest(request: BleRequest){
        bleRequestQueue.addLast(request)
    }


    fun signal(data: ByteArray){
        loopLock.lock()
        loopLock.setData(data)
        loopLock.signal()
        loopLock.unlock()
    }


}